import styled from 'styled-components'
import { formatSecond } from '../../utils/time'
import { useEffect, useState } from 'react'

const Container = styled.div`
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #00000099;
    font-size: 1rem;
`
interface Props {
    seconds?: number,
    onFinished?: () => void;
}

const Countdown: React.FC<Props> = ({ seconds, onFinished }) => {
    const [str, setStr] = useState<string>();


    useEffect(() => {
        let s = seconds;
        if (!s) {
            return;
        }
        setStr(formatSecond(s))
        const timer: NodeJS.Timeout = setInterval(() => {
            s = s! - 1;
            setStr(formatSecond(s))
            if (s === 0) {
                onFinished?.()
                clearInterval(timer)
            }
        }, 1000);

        return () => {
            clearInterval(timer);
        }
    }, [seconds, onFinished])

    return str ? <Container>{str}</Container> : undefined
}

export default Countdown